<template>
  <div class="app-container">
    <!-- 搜索 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleAddNew">+ 添加</el-button>
      <div class="filters">
        <el-select v-model="searchForm.organization" placeholder="组织结构" class="filter-item" clearable>
          <el-option label="信息工程学院" value="信息工程学院" />
          <el-option label="人工智能学院" value="人工智能学院" />
          <el-option label="土木工程学院" value="土木工程学院" />
        </el-select>
        <el-input v-model="searchForm.name" placeholder="请输入姓名" class="filter-item" clearable />
        <el-input v-model="searchForm.account" placeholder="请输入账号" class="filter-item" clearable />
        <el-input v-model="searchForm.leader" placeholder="请输入负责人" class="filter-item" clearable />
        <div class="filter-actions">
          <el-button icon="Search" type="primary" @click="handleSearch">查询</el-button>
          <el-button icon="Remove" @click="handleReset">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 表格 -->
    <div class="table-box">
      <el-table :data="tableData" style="width: 100%" :header-cell-style="{ 'background-color': '#f5f7fa' }">
        <el-table-column prop="interventionTime" label="干预时间" min-width="140"/>
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="account" label="账号" min-width="120"/>
        <el-table-column prop="organization" label="组织结构" min-width="120"/>
        <el-table-column prop="leader" label="负责人" />
        <el-table-column prop="interventionLevel" label="干预级别" min-width="100">
          <template #default="{ row }">
            <span class="status-dot" :class="getInterventionLevelClass(row.interventionLevel)"></span>
            <span class="status-text">{{ row.interventionLevel }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="interventionIssue" label="干预问题" />
        <el-table-column prop="interventionDuration" label="干预时长" />
        <el-table-column prop="closureStatus" label="结案状态" />
        <el-table-column prop="lastModified" label="操作时间" min-width="140" />
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <span class="blue-action" @click="handleView(scope.row)">查看</span>
            <span class="blue-action" @click="handleAdd(scope.row)">编辑</span>
            <span class="red-action" @click="handleDelete(scope.row)">删除</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isViewMode ? '查看干预记录' : (isNameDisabled ? '编辑干预记录' : '添加干预记录')" width="700px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="姓名" prop="name">
          <el-input v-if="!isViewMode" v-model="form.name" />
          <span v-else>{{ form.name }}</span>
        </el-form-item>
        <el-form-item label="负责人" prop="leader">
          <el-input v-if="!isViewMode" v-model="form.leader" />
          <span v-else>{{ form.leader }}</span>
        </el-form-item>
        <el-form-item label="干预内容" prop="interventionContent">
          <el-input v-if="!isViewMode" v-model="form.interventionContent" type="textarea" :rows="3" placeholder="请输入干预内容" />
          <span v-else>{{ form.interventionContent }}</span>
        </el-form-item>
        <el-form-item label="预警级别" prop="warningLevel">
          <el-select v-if="!isViewMode" v-model="form.warningLevel" placeholder="请选择预警级别">
            <el-option label="正常适应" value="正常适应" />
            <el-option label="轻度关注" value="轻度关注" />
            <el-option label="重点关注" value="重点关注" />
            <el-option label="高度风险" value="高度风险" />
            <el-option label="危机状态" value="危机状态" />
          </el-select>
          <span v-else>{{ form.warningLevel }}</span>
        </el-form-item>
        <el-form-item label="干预级别" prop="interventionLevel">
          <el-select v-if="!isViewMode" v-model="form.interventionLevel" placeholder="请选择干预级别">
            <el-option label="常规支持" value="常规支持" />
            <el-option label="一般干预" value="一般干预" />
            <el-option label="加强干预" value="加强干预" />
            <el-option label="重点干预" value="重点干预" />
            <el-option label="危机干预" value="危机干预" />
          </el-select>
          <span v-else>{{ form.interventionLevel }}</span>
        </el-form-item>
        <el-form-item label="干预问题" prop="interventionIssue">
          <el-select v-if="!isViewMode" v-model="form.interventionIssue" placeholder="请选择干预问题">
            <el-option label="学业压力" value="学业压力" />
            <el-option label="家庭关系" value="家庭关系" />
            <el-option label="人际交往" value="人际交往" />
            <el-option label="自我认知" value="自我认知" />
            <el-option label="情绪管理" value="情绪管理" />
            <el-option label="个人成长" value="个人成长" />
            <el-option label="职业生涯" value="职业生涯" />
            <el-option label="亲子关系" value="亲子关系" />
            <el-option label="心理健康" value="心理健康" />
            <el-option label="睡眠障碍" value="睡眠障碍" />
            <el-option label="外貌焦虑" value="外貌焦虑" />
            <el-option label="网络成瘾" value="网络成瘾" />
            <el-option label="创伤应激" value="创伤应激" />
            <el-option label="情感困扰" value="情感困扰" />
            <el-option label="认同迷茫" value="认同迷茫" />
            <el-option label="其他" value="其他" />
          </el-select>
          <span v-else>{{ form.interventionIssue }}</span>
        </el-form-item>
        <el-form-item label="干预时长" prop="interventionDuration">
          <el-input v-if="!isViewMode" v-model.number="form.interventionDuration" />
          <span v-else>{{ form.interventionDuration }}</span>
        </el-form-item>
        <el-form-item label="干预时间" prop="interventionTime">
          <el-date-picker v-if="!isViewMode"
            v-model="form.interventionTime"
            type="datetime"
            placeholder="选择日期时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
          />
          <span v-else>{{ form.interventionTime }}</span>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-if="!isViewMode" v-model="form.remark" type="textarea" />
          <span v-else>{{ form.remark }}</span>
        </el-form-item>
        <el-form-item label="结案状态">
          <el-select v-if="!isViewMode" v-model="form.closureStatus" placeholder="请选择结案状态">
            <el-option label="未结案" value="未结案" />
            <el-option label="解除预警" value="解除预警" />
            <el-option label="转介" value="转介" />
          </el-select>
          <span v-else>{{ form.closureStatus }}</span>
        </el-form-item>
        <el-form-item label="上传文件">
          <div v-if="!isViewMode">
            <el-upload
              action="#"
              :limit="1"
              :on-exceed="handleExceed"
              :before-upload="beforeUpload"
            >
              <div style="display: flex; align-items: center;">
                <el-button type="primary">点击上传</el-button>
                <el-button type="text" @click.stop="handleDownloadTemplate" style="margin-left: 10px;">下载模板</el-button>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  只能上传 <span style="color: #F56C6C; font-weight: 600;">excel, word, ppt, zip</span> 文件，且 <span style="color: #F56C6C; font-weight: 600;">不超过2M</span>
                </div>
              </template>
            </el-upload>
          </div>
          <span v-else>心理干预记录</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button v-if="!isViewMode" @click="handleResetForm">重置</el-button>
          <el-button v-if="!isViewMode" type="primary" @click="handleCreate">{{ isNameDisabled ? '保存修改' : '创建' }}</el-button>
          <el-button v-if="isViewMode" @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { CaretTop, CaretBottom } from '@element-plus/icons-vue';

const searchForm = ref({
  organization: '',
  name: '',
  account: '',
  leader: '',
});

// 排序状态
const sortState = ref({
  field: 'interventionTime',
  order: 'desc' // 'asc' 或 'desc'
});

const allTableData = ref([]);
const tableData = ref([]);

const dialogVisible = ref(false);
const isNameDisabled = ref(false);
const isViewMode = ref(false);
const formRef = ref(null);

const form = ref({
  name: '',
  leader: '',
  interventionContent: '',
  remark: '',
  warningLevel: '',
  interventionLevel: '',
  interventionIssue: '',
  interventionDuration: 1,
  closureStatus: '未结案',
  interventionTime: '',
});

const getInterventionLevelClass = (level) => {
  switch (level) {
    case '危机干预':
      return 'status-high';
    case '重点干预':
      return 'status-medium';
    case '常规支持':
      return 'status-low';
    default:
      return '';
  }
};

const rules = ref({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  leader: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
  interventionContent: [{ required: true, message: '请输入干预内容', trigger: 'blur' }],
  warningLevel: [{ required: true, message: '请选择预警级别', trigger: 'change' }],
  interventionLevel: [{ required: true, message: '请选择干预级别', trigger: 'change' }],
  interventionIssue: [{ required: true, message: '请选择干预问题', trigger: 'change' }],
  interventionDuration: [{ required: true, message: '请输入干预时长', trigger: 'blur' }],
  interventionTime: [{ required: true, message: '请选择干预时间', trigger: 'change' }],
});

const handleDownloadTemplate = () => {
  const link = document.createElement('a');
  link.href = '/心理干预记录 - 模版.docx';
  link.download = '心理干预记录 - 模版.docx';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = (d.getMonth() + 1).toString().padStart(2, '0');
  const day = d.getDate().toString().padStart(2, '0');
  const hours = d.getHours().toString().padStart(2, '0');
  const minutes = d.getMinutes().toString().padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

const saveData = () => {
  sessionStorage.setItem('warningInterventionRecords', JSON.stringify(allTableData.value));
};

onMounted(() => {
  const storedData = sessionStorage.getItem('warningInterventionRecords');
  if (storedData) {
    allTableData.value = JSON.parse(storedData);
  } else {
    // Mock data
    allTableData.value = [
      { id: 1, interventionTime: '2025-03-21 11:18', name: '李明', account: '20250001', organization: '信息工程学院', leader: '陈老师', warningLevel: '危机状态', interventionLevel: '危机干预', interventionIssue: '学业压力', interventionDuration: 1, closureStatus: '未结案', lastModified: '2025-03-21 14:30' },
      { id: 2, interventionTime: '2025-03-21 09:45', name: '张亮亮', account: '20250002', organization: '人工智能学院', leader: '李老师', warningLevel: '高度风险', interventionLevel: '重点干预', interventionIssue: '家庭关系', interventionDuration: 1, closureStatus: '解除预警', lastModified: '2025-03-21 16:20' },
      { id: 3, interventionTime: '2025-03-21 15:30', name: '王小红', account: '20250003', organization: '土木工程学院', leader: '王老师', warningLevel: '正常适应', interventionLevel: '常规支持', interventionIssue: '人际交往', interventionDuration: 1, closureStatus: '转介', lastModified: '2025-03-21 10:15' },
    ];
    saveData();
  }
  tableData.value = allTableData.value;
});

const handleSearch = () => {
  let filteredData = allTableData.value.filter(item => {
    return (
      (!searchForm.value.organization || item.organization.includes(searchForm.value.organization)) &&
      (!searchForm.value.name || item.name.includes(searchForm.value.name)) &&
      (!searchForm.value.account || item.account.includes(searchForm.value.account)) &&
      (!searchForm.value.leader || item.leader.includes(searchForm.value.leader))
    );
  });

  // 应用排序
  if (sortState.value.field === 'interventionTime') {
    filteredData.sort((a, b) => {
      const dateA = new Date(a.interventionTime);
      const dateB = new Date(b.interventionTime);
      return sortState.value.order === 'asc' ? dateA - dateB : dateB - dateA;
    });
  }

  tableData.value = filteredData;
};

const handleReset = () => {
  searchForm.value = {
    organization: '',
    name: '',
    account: '',
    leader: '',
  };
  tableData.value = allTableData.value;
};

// 排序切换函数
const handleSort = (field) => {
  if (sortState.value.field === field) {
    // 切换排序方向
    sortState.value.order = sortState.value.order === 'asc' ? 'desc' : 'asc';
  } else {
    // 新字段，默认降序
    sortState.value.field = field;
    sortState.value.order = 'desc';
  }
  handleSearch(); // 重新应用搜索和排序
};

const handleAddNew = () => {
  handleResetForm();
  isNameDisabled.value = false;
  isViewMode.value = false;
  dialogVisible.value = true;
};

const handleView = (row) => {
  isViewMode.value = true;
  isNameDisabled.value = false; // 查看模式下姓名字段可编辑
  form.value = {
    name: row.name,
    leader: row.leader,
    interventionContent: '无',
    warningLevel: '危机状态',
    interventionLevel: '危机干预',
    interventionIssue: '学业压力',
    interventionDuration: row.interventionDuration || 1,
    closureStatus: row.closureStatus || '未结案',
    interventionTime: row.interventionTime,
    remark: row.remark || ''
  };
  dialogVisible.value = true;
};

const handleAdd = (row) => {
  handleResetForm();
  form.value.name = row.name;
  form.value.leader = row.leader;
  form.value.interventionTime = row.interventionTime;
  isNameDisabled.value = true; // 编辑模式下标记为已禁用状态
  isViewMode.value = false;
  dialogVisible.value = true;
};

const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该条记录吗?',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    allTableData.value = allTableData.value.filter(item => item.id !== row.id);
    saveData();
    handleSearch();
    ElMessage({
      type: 'success',
      message: '删除成功',
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除',
    });
  });
};

const handleCreate = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const newRecord = {
        ...form.value,
        id: Date.now(),
        account: 'newuser', // This should be dynamic in a real app
        organization: '学院C', // This should be dynamic in a real app
        lastModified: new Date().toISOString().split('T')[0],
        interventionTime: formatDate(form.value.interventionTime),
      };
      allTableData.value.push(newRecord);
      saveData();
      handleSearch();
      dialogVisible.value = false;
    } else {
      ElMessage.error('请填写所有必填项');
      return false;
    }
  });
};

const handleResetForm = () => {
  form.value = {
    name: '',
    leader: '',
    interventionContent: '',
    remark: '',
    warningLevel: '',
    interventionLevel: '',
    interventionIssue: '',
    interventionDuration: 1,
    closureStatus: '未结案',
    interventionTime: '',
  };
  isViewMode.value = false;
  isNameDisabled.value = false;
  if (formRef.value) {
    formRef.value.clearValidate();
  }
};

const handleExceed = () => {
  ElMessage.warning('只能上传一个文件');
};

const beforeUpload = (file) => {
  const isLt2M = file.size / 1024 / 1024 < 2;
  const isAcceptedType = [
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-powerpoint',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'application/zip',
  ].includes(file.type);

  if (!isAcceptedType) {
    ElMessage.error('上传文件格式不正确!');
  }
  if (!isLt2M) {
    ElMessage.error('上传文件大小不能超过 2MB!');
  }
  return isAcceptedType && isLt2M;
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.action-bar {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
}
.filters {
  display: flex;
  flex-wrap: wrap;
  margin-left: 20px;
  gap: 12px;
}
.filter-item {
  width: 200px;
}
.filter-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}
.table-box {
  margin-bottom: 20px;
}
.dialog-footer {
  text-align: right;
}
.blue-action {
  color: #409EFF;
  margin-right: 12px;
  cursor: pointer;
  user-select: none;
}
.red-action {
  color: #F56C6C;
  margin-right: 12px;
  cursor: pointer;
  user-select: none;
}

/* 排序箭头样式 */
.sortable-header {
  display: flex;
  align-items: center;
  cursor: pointer;
  user-select: none;
}
.sort-arrows {
  display: flex;
  flex-direction: column;
  margin-left: 4px;
  gap: 1px;
}
.arrow-up,
.arrow-down {
  color: #ccc;
  transition: color 0.2s;
}
.arrow-up.active {
  color: #409EFF;
}
.arrow-down.active {
  color: #409EFF;
}
.arrow-up:hover,
.arrow-down:hover {
  color: #666;
}

/* 干预级别状态点样式 */
.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 8px;
}
.status-high {
  background-color: red;
}
.status-medium {
  background-color: orange;
}
.status-low {
  background-color: green;
}
</style>
